package com.devplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.devplatform.mapper.FansMapper;
import com.devplatform.mapper.user.UserMapper;
import com.devplatform.pojo.Fans;
import com.devplatform.pojo.dto.FollowDto;
import com.devplatform.pojo.user.User;
import com.devplatform.pojo.vo.DataVo;
import com.devplatform.service.FansService;
import com.devplatform.util.MessageUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jnks03
 * @description 针对表【fans】的数据库操作Service实现
 * @createDate 2025-09-30 16:23:36
 */
@Service
@Log4j2
public class FansServiceImpl extends ServiceImpl<FansMapper, Fans>
        implements FansService {
    @Autowired
    private final UserService userService;
    @Autowired
    private MessageUtil messageUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FansMapper fansMapper;

    public FansServiceImpl(UserService userService) {
        this.userService = userService;
    }

    //检查关注情况
    @Override
    public DataVo toggleFollow(Long fansId, FollowDto authorDto) {
        Long authorId = authorDto.getAuthorId();
        // 校验：不能操作自己
        if (fansId.equals(authorId)) {
            return DataVo.error("不能关注自己");
        }
        // 条件构造器：查询有效关注记录
        LambdaQueryWrapper<Fans> queryWrapper = new LambdaQueryWrapper<Fans>();
        queryWrapper.eq(Fans::getFansId, fansId)
                .eq(Fans::getAuthorId, authorId);
        boolean exists = exists(queryWrapper);
        if (exists) {
            // 存在：取消关注
            LambdaUpdateWrapper<Fans> updateWrapper = new LambdaUpdateWrapper<Fans>();
            updateWrapper.eq(Fans::getFansId, fansId)
                    .eq(Fans::getAuthorId, authorId);
            boolean removeResult = remove(updateWrapper);

            if (removeResult) {
                // 操作后状态：未关注
                return DataVo.ok("取消关注成功");
            } else {
                return DataVo.ok("取消关注失败");

            }
        } else {
            // 不存在：新增关注
            Fans fans = new Fans();
            fans.setFansId(fansId);
            fans.setAuthorId(authorId); //设置被关注用户ID
            fans.setAttentionTime(LocalDateTime.now()); // 补充设置关注时间（如果表中有该字段）
            boolean saveResult = save(fans);
            if (saveResult) {

                User fanUser = userMapper.selectById(fansId);
                String fanName = fanUser != null ? fanUser.getUsername() : "用户";

                String title = "新关注通知";
                String content = String.format("用户【%s】关注了你，快去看看吧～", fanName);

                Map<String, Object> extraData = new HashMap<>();
                extraData.put("fansId", fansId); // 关注者ID，便于跳转其主页

                messageUtil.sendSystemMessage(authorId, title, content, extraData);

                return DataVo.ok("关注成功");
            } else {
                return DataVo.error("关注失败");
            }
        }
    }

    @Override
    public DataVo getFansCount(Long userId) {
        LambdaQueryWrapper<Fans> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Fans::getAuthorId, userId);
        Integer fansCount = Math.toIntExact(count(queryWrapper));
        return DataVo.ok(fansCount);
    }

//    @Override
//    public DataVo getFansList(IPage<Fans> fansIPage, Long userId) {
//        LambdaQueryWrapper<Fans> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Fans::getAuthorId, userId).eq(Fans::getIsDeleted, 0);
//        page(fansIPage, queryWrapper);
//        return DataVo.ok(fansIPage);
//    }

    @Override
    public DataVo getFansList(IPage<Fans> fansIPage, Long userId) {
        // 需要关联用户表查询粉丝的详细信息
        LambdaQueryWrapper<Fans> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Fans::getAuthorId, userId)
                .orderByDesc(Fans::getAttentionTime);
        IPage<Fans> pageResult = page(fansIPage, queryWrapper);
        // 获取粉丝的详细信息
        List<Fans> fansList = pageResult.getRecords();
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Fans fans : fansList) {
            Map<String, Object> fanInfo = new HashMap<>();
            fanInfo.put("id", fans.getId());
            fanInfo.put("fansId", fans.getFansId().toString());
            fanInfo.put("attentionTime", fans.getAttentionTime());
            // 查询粉丝用户信息
            User fanUser = userService.getById(fans.getFansId());
            if (fanUser != null) {
                fanInfo.put("username", fanUser.getUsername());
                fanInfo.put("avatar", fanUser.getAvatar());
                fanInfo.put("briefly", fanUser.getBriefly());
            }
            resultList.add(fanInfo);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("records", resultList);
        result.put("total", pageResult.getTotal());
        result.put("size", pageResult.getSize());
        result.put("current", pageResult.getCurrent());
        result.put("pages", pageResult.getPages());
        return DataVo.ok(result);
    }


//    @Override
//    public DataVo getFollowingList(IPage<Fans> fansIPage, Long userId) {
//        LambdaQueryWrapper<Fans> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Fans::getFansId, userId).eq(Fans::getIsDeleted, 0);
//        queryWrapper.orderByDesc(Fans::getAttentionTime);
//        page(fansIPage, queryWrapper);
//        return DataVo.ok(fansIPage);
//    }

    @Override
    public DataVo getFollowingList(IPage<Fans> fansIPage, Long userId) {
        LambdaQueryWrapper<Fans> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Fans::getFansId, userId)
                .orderByDesc(Fans::getAttentionTime);
        IPage<Fans> pageResult = page(fansIPage, queryWrapper);
        // 获取关注用户的详细信息
        List<Fans> followingList = pageResult.getRecords();
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Fans following : followingList) {
            Map<String, Object> followInfo = new HashMap<>();
            followInfo.put("id", following.getId());
            followInfo.put("authorId", following.getAuthorId().toString());
            followInfo.put("attentionTime", following.getAttentionTime());
            // 查询被关注用户信息
            User authorUser = userService.getById(following.getAuthorId());
            if (authorUser != null) {
                followInfo.put("username", authorUser.getUsername());
                followInfo.put("avatar", authorUser.getAvatar());
                followInfo.put("briefly", authorUser.getBriefly());
            }
            resultList.add(followInfo);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("records", resultList);
        result.put("total", pageResult.getTotal());
        result.put("size", pageResult.getSize());
        result.put("current", pageResult.getCurrent());
        result.put("pages", pageResult.getPages());
        return DataVo.ok(result);
    }

    @Override
    public DataVo getFansStatistics(Long userId) {
        Map<String, Object> statistics = new HashMap<>();
        //粉丝的总数量
        LambdaQueryWrapper<Fans> fansQuery = new LambdaQueryWrapper<>();
        fansQuery.eq(Fans::getAuthorId, userId);
        Long fansCount = count(fansQuery);
        statistics.put("totalFans", fansCount);
        //关注的总数量
        LambdaQueryWrapper<Fans> followQuery = new LambdaQueryWrapper<>();
        followQuery.eq(Fans::getFansId, userId);
        Long followCount = count(followQuery);
        statistics.put("totalFollow", followCount);
        return DataVo.ok(statistics);
    }

    @Override
    public DataVo getFansAnalysis(Long userId) {
        Map<String, Object> analysis = new HashMap<>();
        //粉丝增长的趋势(最近一周)
        List<Map<String, Object>> growthTrend = new ArrayList<>();
        for (int i = 6; i >= 0; i--) {
            LocalDateTime endDate = LocalDateTime.now().minusDays(i);
            LocalDateTime startDate = endDate.minusDays(1);
            LambdaQueryWrapper<Fans> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Fans::getAuthorId, userId)
                    .between(Fans::getAttentionTime, startDate, endDate);
            Long dailyFans = count(queryWrapper);
            Map<String, Object> dayData = new HashMap<>();
            dayData.put("date", endDate.toLocalDate().toString());
            dayData.put("count", dailyFans);
            growthTrend.add(dayData);
        }
        analysis.put("growthTrend", growthTrend);

        return DataVo.ok(analysis);
    }

    @Override
    public boolean isFollowing(Long fansId, Long authorId) {
        LambdaQueryWrapper<Fans> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Fans::getFansId, fansId)
                .eq(Fans::getAuthorId, authorId);
        return count(queryWrapper) > 0;
    }

    //搜索粉丝
    @Override
    public DataVo searchFans(IPage<Fans> fansIPage, Long userId, String keyword) {
        LambdaQueryWrapper<Fans> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Fans::getAuthorId, userId)
                .orderByDesc(Fans::getAttentionTime);
        // 执行分页查询
        IPage<Fans> pageResult = page(fansIPage, queryWrapper);
        List<Fans> fansList = pageResult.getRecords();
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Fans fans : fansList) {
            // 查询粉丝用户信息
            User fanUser = userService.getById(fans.getFansId());
            if (fanUser != null) {
                if (keyword != null && !keyword.trim().isEmpty()) {
                    if (fanUser.getUsername() != null &&
                            fanUser.getUsername().toLowerCase().contains(keyword.toLowerCase())) {
                        resultList.add(buildFanInfo(fans, fanUser));
                    }
                } else {
                    resultList.add(buildFanInfo(fans, fanUser));
                }
            }
        }
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("records", resultList);
        result.put("total", resultList.size());
        result.put("size", pageResult.getSize());
        result.put("current", pageResult.getCurrent());
        result.put("pages", (int) Math.ceil((double) resultList.size() / pageResult.getSize()));
        return DataVo.ok(result);
    }

    //搜索关注
    @Override
    public DataVo searchFollowing(IPage<Fans> fansIPage, Long userId, String keyword) {
        LambdaQueryWrapper<Fans> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Fans::getFansId, userId)
                .orderByDesc(Fans::getAttentionTime);
        // 执行分页查询
        IPage<Fans> pageResult = page(fansIPage, queryWrapper);
        List<Fans> followingList = pageResult.getRecords();
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Fans following : followingList) {
            // 查询被关注用户信息
            User authorUser = userService.getById(following.getAuthorId());
            if (authorUser != null) {
                if (keyword != null && !keyword.trim().isEmpty()) {
                    if (authorUser.getUsername() != null &&
                            authorUser.getUsername().toLowerCase().contains(keyword.toLowerCase())) {
                        resultList.add(buildFollowingInfo(following, authorUser));
                    }
                } else {
                    resultList.add(buildFollowingInfo(following, authorUser));
                }
            }
        }
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("records", resultList);
        result.put("total", resultList.size());
        result.put("size", pageResult.getSize());
        result.put("current", pageResult.getCurrent());
        result.put("pages", (int) Math.ceil((double) resultList.size() / pageResult.getSize()));
        return DataVo.ok(result);
    }

    // 构建粉丝信息
    private Map<String, Object> buildFanInfo(Fans fans, User fanUser) {
        Map<String, Object> fanInfo = new HashMap<>();
        fanInfo.put("id", fans.getId());
        fanInfo.put("fansId", fans.getFansId());
        fanInfo.put("attentionTime", fans.getAttentionTime());
        fanInfo.put("username", fanUser.getUsername());
        fanInfo.put("avatar", fanUser.getAvatar());
        fanInfo.put("briefly", fanUser.getBriefly());
        return fanInfo;
    }

    // 构建关注信息
    private Map<String, Object> buildFollowingInfo(Fans following, User authorUser) {
        Map<String, Object> followInfo = new HashMap<>();
        followInfo.put("id", following.getId());
        followInfo.put("authorId", following.getAuthorId());
        followInfo.put("attentionTime", following.getAttentionTime());
        followInfo.put("username", authorUser.getUsername());
        followInfo.put("avatar", authorUser.getAvatar());
        followInfo.put("briefly", authorUser.getBriefly());
        return followInfo;
    }
}




